<template>
  <div>
    <PageSearchTableWrappe>
      <template #search>
        <a-form layout="inline" :model="searchValue">
          <a-form-item>
            <a-input v-model:value="searchValue.name" allowClear placeholder="部门名称"> </a-input>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" @click="handleSearch">查询 </a-button>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleCreate">新增部门 </a-button>
          </a-form-item>
        </a-form>
      </template>

      <template #table>
        <a-table
          :columns="columns"
          :data-source="data"
          rowKey="id"
          :loading="dataLoading"
          :pagination="false"
          v-model:expandedRowKeys="expandedRowKeys"
          @expand="onExpand"
        >
          <template #bodyCell="{ text, column, record }">
            <template v-if="column.dataIndex === 'name'">
              <span v-if="text.indexOf(searchValue.name) > -1">
                {{ text.substr(0, text.indexOf(searchValue.name)) }}
                <span style="color: #f50">{{ searchValue.name }}</span>
                {{ text.substr(text.indexOf(searchValue.name) + searchValue.name.length) }}
              </span>
              <span v-else>{{ text }}</span>
            </template>

            <template v-if="column.dataIndex === 'operation'">
              <span>
                <a @click="handleEdit(record)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm title="确认删除吗?" @confirm="handleDelete(record)">
                  <a href="#">删除</a>
                </a-popconfirm>
              </span>
            </template>
          </template>
        </a-table>
      </template>
    </PageSearchTableWrappe>

    <DeptModal v-model:visible="openModal" :data="modalData" @ok="handleModalOK" />
  </div>
</template>
<script lang="ts">
export default {
  name: 'DeptManagement',
};
</script>
<script setup lang="ts">
import { ref, onMounted, computed, watch, h } from 'vue';
import { message } from 'ant-design-vue';
import { Tag } from 'ant-design-vue';
import { Icon } from '/@/components/Icon';
import { getDeptList, deleteDept } from '/@/api/sys/system';
import { PageSearchTableWrappe } from '/@/components/Page';
import DeptModal from './DeptModal.vue';

const columns = [
  {
    title: '部门名称',
    dataIndex: 'name',
    align: 'left',
  },
  {
    title: '排序',
    dataIndex: 'sorts',
  },
  {
    title: '状态',
    dataIndex: 'status',
    customRender: ({ record }) => {
      const status = record.status;
      const enable = ~~status === 1;
      const color = enable ? 'green' : 'red';
      const text = enable ? '启用' : '停用';
      return h(Tag, { color: color }, () => text);
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '创建人',
    dataIndex: 'creator',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    fixed: 'right',
  },
];

const statusOptions = [
  { label: '启用', value: 1 },
  { label: '停用', value: 2 },
];

const searchValue = ref({
  status: undefined,
  name: '',
});

const openModal = ref(false);
const modalData = ref({});

const data = ref([]);
const expandedRowKeys = ref([]);
const dataLoading = ref(false);
const fetchData = async () => {
  dataLoading.value = true;
  try {
    data.value = await getDeptList();
    expandedRowKeys.value.push(data.value[0]?.id);
    generateList(data.value);
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
onMounted(() => {
  fetchData();
});

const dataList = [];
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    dataList.push(node);
    if (node.children) {
      generateList(node.children);
    }
  }
};

const getParentKey = (id, keys) => {
  for (let i = 0; i < dataList.length; i++) {
    const node = dataList[i];
    if (node.id == id) {
      if (node.parentId != 0) {
        getParentKey(node.parentId, keys);
      }
      keys.push(node.id);
    }
  }
  return keys;
};

const getExpandedKeys = (searchValue, keys) => {
  for (let i = 0; i < dataList.length; i++) {
    const node = dataList[i];
    if (node.name.indexOf(searchValue.name) > -1) {
      keys.push(node.id);
      keys.push.apply(keys, getParentKey(node.parentId, []));
    }
  }
  return keys;
};

const onExpand = (expanded, record) => {
  // if (expanded) {
  //   // 设置展开窗Key
  //   expandedRowKeys.value.push(record.id);
  // } else {
  //   if (expandedRowKeys.value.length) {
  //     expandedRowKeys.value = expandedRowKeys.value.filter((v) => {
  //       return v != record.id;
  //     });
  //   }
  // }
};

const handleSearch = () => {
  if (!searchValue.value.name) return;
  const expanded = getExpandedKeys(searchValue.value, []);
  expandedRowKeys.value = [...expanded];
};

function handleCreate() {
  openModal.value = true;
  modalData.value = {};
}

function handleEdit(record: Recordable) {
  openModal.value = true;
  modalData.value = record;
}

const handleDelete = async (record: Recordable) => {
  const { id } = record;
  await deleteDept({ id: id });
  message.success('删除成功');
  fetchData();
};

const handleModalOK = (result) => {
  fetchData();
};
</script>
